import { log } from "console";
import type { MqttClient, OnMessageCallback } from "mqtt";
import * as mqtt from "mqtt/dist/mqtt.min.js";

/**
 * connectMqtt(host: string, port: number, user: string, pwd: string, id: string, clean: boolean)
 * connectMqtt('127.0.0.1', 1883, 'test', '123456', 'this_is_test_200507_nodejs_oilfume_2', true);
 */
export default class MQTT {
  //公共变量
  url: string; // mqtt地址
  topic: string; //订阅主题
  client!: MqttClient;
  constructor(topic: string) {
    this.topic = topic;
    // 虽然是mqtt但是在客户端这里必须采用websock的链接方式
    this.url = "http://47.103.39.74:21883/mqtt";
  }

  //初始话mqtt
  init() {
    const options = {
      clean: true, // 保留会话
      host: "47.103.39.74",
      // 认证信息
      clientId: "CmdSub_338222112334", //链接id
      password: "admin",
      username: "admin",
      connectTimeout: 4000, // 超时时间
      reconnectPeriod: 4000, // 重连时间间隔
    };
    this.client = mqtt.connect(this.url, options);
    this.client.on("error", (error: any) => {
      console.log(error);
    });
    this.client.on("reconnect", (error: Error) => {
      console.log(error);
    });
  }

  //取消订阅
  unsubscribes() {
    this.client.unsubscribe(this.topic, (error: any) => {
      if (!error) {
        console.log("取消订阅成功");
      } else {
        console.log("取消订阅失败");
      }
    });
  }

  //连接
  link() {
    this.client.on("connect", (e) => {
      this.client.subscribe(this.topic, (error: any) => {
        if (!error) {
          console.log("订阅成功");
        } else {
          console.log("订阅失败");
        }
      });
    });
  }

  //收到的消息
  get(callback: OnMessageCallback) {
    this.client.on("message", callback);
  }

  //结束链接
  over() {
    this.client.end();
  }
}
/*
 * 来源作者：你的微笑暖暖的
 * 链接：https://juejin.cn/post/7130915751304626206
 */
